<script setup lang="ts">
import useToast from '@/hooks/useToast';
import HomeRequest from '@/request/homeRequest';
import { useAppStore } from '@/store';
import to from '@/utils/to';

interface IProps {
  data: IGoodsAdditionalInfo;
}

type EmitEvents = {
  (event: 'change', payload: { value: string }): void;
  (event: 'IDCardChange', payload: IObtainUserDataByIDCardRes): void;
};

const props = defineProps<IProps>();
const store = useAppStore();
const emits = defineEmits<EmitEvents>();
const _value = ref<string>(props.data.value || '');
const { showToast } = useToast();

watch(
  () => props.data,
  (data) => {
    _value.value = data.value;
  },
);

// 根据身份证获取用户数据
const fetchObtainUserDataByIDCard = async () => {
  if (!_value.value) {
    showToast('请先输入患者身份证号码');
    return;
  }
  const [err, res] = await to(HomeRequest.ObtainUserDataByIDCard({ idCard: _value.value, variantId: store.$state.shoppingCart[0].variantId }));
  if (err) return;
  emits('IDCardChange', res.data);
};

// 扫码
const handleScanCode = () => {
  uni.scanCode({
    scanType: ['barCode', 'qrCode'],
    success: function (res) {
      _value.value = res.result;
      emits('change', { value: _value.value });
    },
  });
};

// input change
const handleInputChange = (value: string) => {
  _value.value = value;
  emits('change', { value });
};
</script>

<template>
  <van-field clearable clickable :value="_value" :placeholder="`请输入${props.data.attrName}`" :required="props.data.requiredFlag" @change="handleInputChange($event.detail)">
    <text slot="label" class="c-text-12">{{ props.data.attrName }}</text>
    <i v-if="props.data.fieldName === 'barcode'" slot="right-icon" class="i-f7:qrcode-viewfinder text-20px" @click="handleScanCode" />
    <i v-if="props.data.fieldName === 'patientCard' && props.data.dockData === 'cxry'" slot="right-icon" class="i-icon-park-outline:doc-search text-20px" @click="fetchObtainUserDataByIDCard"></i>
  </van-field>
</template>
